<script setup>
    import { ref } from "vue";
    import { ElMessage } from "element-plus";
    // 引入 api 接口
    import { updatePwd } from "@/api/user.js";
    // 引入 token 和 userInfo 状态管理
    import { useUserInfoStore } from "@/stores/userInfo.js";
    import { useTokenStore } from "@/stores/token.js";
    const userInfoStore = useUserInfoStore();
    const tokenStore = useTokenStore();
    // 引入路由
    import { useRouter } from "vue-router";
    const router = useRouter();

    // 表单模型
    const formData = ref({
        old_pwd: "",
        new_pwd: "",
        re_pwd: "",
    });

    // 表单验证规则

    // 自定义表单验证规则
    const checkRePassword = (rule, value, callback) => {
        if (!value || value == null) {
            return callback(new Error("请再次输入密码"));
        }
        if (value != formData.value.new_pwd) {
            return callback(new Error("两次输入密码不一致，请重新输入"));
        }
    };

    //添加分类表单校验
    const rules = {
        old_pwd: [{ required: true, message: "请输入旧密码", trigger: "blur" }],
        new_pwd: [
            { required: true, message: "请输入分类别名", trigger: "blur" },
        ],
        re_pwd: [{ validator: checkRePassword, trigger: "blur" }],
    };

    // 更新函数
    const update = async () => {
        // 发送请求
        const result = await updatePwd(formData.value);
        ElMessage.success(result.message ? result.message : "修改成功");

        // 删除 token
        tokenStore.removeToken();
        // 删除 userInfo
        userInfoStore.removeUserInfo();
        // 跳转至登陆页面
        router.push("/login");
    };
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>重置密码</span>
            </div>
        </template>
        <el-row>
            <el-col :span="12">
                <el-form
                    :model="formData"
                    :rules="rules"
                    label-width="100px"
                    size="large"
                >
                    <el-form-item label="旧密码" prop="old_pwd">
                        <el-input v-model="formData.old_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码" prop="new_pwd">
                        <el-input v-model="formData.new_pwd"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="re_pwd">
                        <el-input v-model="formData.re_pwd"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="update"
                            >提交修改</el-button
                        >
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>
    </el-card>
</template>
